<template>
  <j-modal
    title="打印入库单"
    :width="800"
    :visible="visible"
    :footer="null"
    @cancel="handleCancel">
    
    <a-spin :spinning="confirmLoading">
      <div id="printArea" class="print-content" :class="{'transfer-mode': model.businessType == '13'}">
        <div class="print-header">
          <h1>入库单</h1>
          <div class="print-info">
            <div class="print-info-item">
              <span class="label">入库单号：</span>
              <span class="value">{{ model.inboundNo }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">计划入库日期：</span>
              <span class="value">
                <span class="date-picker-wrapper" @click.stop="showDatePicker">
                  <span v-if="!datePickerVisible" class="signature-line">{{ model.planInboundTime || '' }}</span>
                  <a-date-picker 
                    v-if="datePickerVisible"
                    v-model="planInboundTime" 
                    format="YYYY-MM-DD" 
                    placeholder="请选择计划入库时间"
                    style="width: 100%"
                    @change="handlePlanTimeChange"
                    @blur="hideDatePicker"
                    @click.stop />
                </span>
              </span>
            </div>
            <div class="print-info-item">
              <span class="label">业务类型：</span>
              <span class="value">{{ model.businessTypeName }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">业务单号：</span>
              <span class="value">{{ model.businessNo || '' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">批次号：</span>
              <span class="value">{{ model.batchNo || '' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">入库单状态：</span>
              <span class="value">{{ model.statusName }}</span>
            </div>
            <div class="print-info-item" style="width: 100%">
              <span class="label">备注：</span>
              <span class="value">{{ model.remark || '' }}</span>
            </div>
          </div>
        </div>
        
        <!-- 物料明细信息 -->
        <div class="print-table-container">
          <h2>物料明细信息</h2>
          <table class="print-table">
            <thead>
              <tr v-if="model.businessType != '13'">
                <th>物料编码</th>
                <th>物料名称</th>
                <th>物料类型</th>
                <th>规格</th>
                <th>单位</th>
                <th>计划入库仓库/库位</th>
                <th>实际入库仓库/库位</th>
                <th>计划数量</th>
                <th>实际数量</th>
                <th>单位成本</th>
                <th>状态</th>
              </tr>
              <tr v-else>
                <th>物料编码</th>
                <th>物料名称</th>
                <th>物料类型</th>
                <th>单位</th>
                <th>原仓库/原库位</th>
                <th>计划入库仓库/库位</th>
                <th>实际入库仓库/库位</th>
                <th>计划数量</th>
                <th>实际数量</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(record, index) in detailList" :key="record.id || record.materialCode" :class="getRowClassName(record, index)">
                <template v-if="model.businessType != '13'">
                  <td>{{ record.materialCode }}</td>
                  <td>{{ record.materialName }}</td>
                  <td>{{ record.materialTypeName }}</td>
                  <td>{{ record.specification }}</td>
                  <td>{{ record.unit }}</td>
                  <td>{{ record.planWarehouseName }}/{{ record.planLocationName }}</td>
                  <td>{{ record.actualWarehouseName }} {{ record.actualLocationName }}</td>
                  <td>{{ record.planQuantity }}</td>
                  <td>{{ record.actualQuantity || '' }}</td>
                  <td>{{ record.unitCost || '' }}</td>
                  <td>{{ getDetailStatus(record) }}</td>
                </template>
                <template v-else>
                  <td>{{ record.materialCode }}</td>
                  <td>{{ record.materialName }}</td>
                  <td>{{ record.materialTypeName }}</td>
                  <td>{{ record.unit }}</td>
                  <td>{{ record.sourceWarehouseName || '-' }}/{{ record.sourceLocationName || '-' }}</td>
                  <td>{{ record.planWarehouseName }}/{{ record.planLocationName }}</td>
                  <td>{{ record.actualWarehouseName }} {{ record.actualLocationName }}</td>
                  <td>{{ record.planQuantity }}</td>
                  <td>{{ record.actualQuantity || '' }}</td>
                  <td>{{ getDetailStatus(record) }}</td>
                </template>
              </tr>
              <tr v-if="detailList.length === 0">
                <td :colspan="model.businessType === '13' ? 10 : 11">无明细数据</td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 状态信息 -->
        <div class="print-table-container">
          <h2>汇总信息</h2>
          <table class="print-table">
            <thead>
              <tr>
                <th width="33%">总计划入库数量</th>
                <th width="33%">总实际入库数量</th>
                <th width="34%">创建时间</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>{{ model.totalPlanQuantity || '' }}</td>
                <td></td>
                <td>{{ model.createTime }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="print-footer">
          <div class="print-signature">
            <div class="signature-item">
              <span>仓库管理员：</span>
              <span class="signature-line"></span>
            </div>
            <div class="signature-item">
              <span>入库操作人：</span>
              <span class="signature-line"></span>
            </div>
            <div class="signature-item">
              <span>入库日期：</span>
              <span class="signature-line"></span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="print-actions">
        <a-button type="primary" icon="printer" @click="handlePrint">打印</a-button>
        <a-button style="margin-left: 8px" icon="download" @click="handleExport">导出PDF</a-button>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
  import { getAction } from '@/api/manage'
  // 使用import方式导入jspdf
  import jsPDF from 'jspdf'
  import html2canvas from 'html2canvas'
  import moment from 'moment'
  
  export default {
    name: 'InboundPrintModal',
    data() {
      return {
        visible: false,
        model: {},
        detailList: [], // 添加明细列表数据
        planInboundTime: null, // 计划入库时间
        confirmLoading: false,
        datePickerVisible: false, // 日期选择器是否可见
        columns: [
          { title: '物料编码', dataIndex: 'materialCode', width: '8%' },
          { title: '物料名称', dataIndex: 'materialName', width: '10%' },
          { title: '物料类型', dataIndex: 'materialTypeName', width: '7%' },
          { title: '规格', dataIndex: 'specification', width: '8%' },
          { title: '单位', dataIndex: 'unit', width: '5%' },
          { 
            title: '计划入库仓库/库位', 
            dataIndex: 'planWarehouseName', 
            width: '12%',
            customRender: (text, record) => {
              return `${record.planWarehouseName || ''}/${record.planLocationName || ''}`;
            }
          },
          { 
            title: '实际入库仓库/库位', 
            dataIndex: 'actualWarehouseName', 
            width: '12%',
            customRender: (text, record) => {
              return `${record.actualWarehouseName || ''} ${record.actualLocationName || ''}`;
            }
          },
          { title: '计划数量', dataIndex: 'planQuantity', width: '8%' },
          { title: '实际数量', dataIndex: 'actualQuantity', width: '8%' },
          { title: '单位成本', dataIndex: 'unitCost', width: '10%' },
          { title: '状态', dataIndex: 'status', width: '12%' }
        ],
        url: {
          getInboundOrder: '/wms/inboundOrder/queryById',
          getDetailList: '/wms/inboundOrder/queryDetailList'
        }
      }
    },
    mounted() {
      // 添加全局点击事件，用于关闭日期选择器
      document.addEventListener('click', this.handleGlobalClick);
    },
    beforeDestroy() {
      // 移除全局点击事件监听器
      document.removeEventListener('click', this.handleGlobalClick);
    },
    methods: {
      // 处理全局点击事件
      handleGlobalClick() {
        if (this.datePickerVisible) {
          this.datePickerVisible = false;
        }
      },
      
      show(id) {
        this.visible = true
        this.loadData(id)
      },
      
      // 处理计划入库时间变更
      handlePlanTimeChange(date, dateString) {
        if (this.model.id) {
          // 确保日期格式为YYYY-MM-DD
          this.model.planInboundTime = moment(date).format('YYYY-MM-DD')
          console.log('计划入库时间已更新:', this.model.planInboundTime)
          
          // 自动隐藏日期选择器，避免需要额外点击
          this.hideDatePicker();
        }
      },
      
      // 显示日期选择器
      showDatePicker() {
        // 防止重复触发
        if (this.datePickerVisible) return;
        
        this.datePickerVisible = true;
        
        // 使用nextTick确保DOM已更新后聚焦
        this.$nextTick(() => {
          // 使用更精确的选择器并添加错误处理
          try {
            const datePicker = document.querySelector('.date-picker-wrapper .ant-calendar-picker-input');
            if (datePicker) {
              setTimeout(() => {
                datePicker.click();
              }, 50);
            }
          } catch (error) {
            console.error('日期选择器聚焦失败:', error);
            // 如果聚焦失败，自动隐藏日期选择器，避免界面卡死
            this.datePickerVisible = false;
          }
        });
      },
      
      // 隐藏日期选择器
      hideDatePicker() {
        // 延迟隐藏以确保日期已选择
        setTimeout(() => {
          this.datePickerVisible = false;
        }, 300);
      },
      
      // 获取明细状态
      getDetailStatus(detail) {
        if (detail.actualQuantity && detail.actualQuantity >= detail.planQuantity) {
          return '已完成';
        } else if (detail.actualQuantity && detail.actualQuantity > 0) {
          return '部分入库';
        } else {
          return '待入库';
        }
      },
      
      // 获取行样式
      getRowClassName(record, index) {
        let className = '';
        if (index % 2 === 1) {
          className += 'even-row';
        }
        return className;
      },
      
      batchPrint(ids) {
        if (!ids || ids.length === 0) {
          this.$message.warning('请选择要打印的入库单')
          return
        }
        
        // 打开批量打印窗口
        const printWindow = window.open('', '_blank')
        printWindow.document.write(`
          <html>
            <head>
              <title>批量打印入库单</title>
              <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
                .page-break { page-break-after: always; }
                .print-content { padding: 20px; max-width: 800px; margin: 0 auto; }
                .print-header { text-align: center; margin-bottom: 20px; }
                .print-header h1 { font-size: 24px; font-weight: bold; margin-bottom: 20px; }
                .print-info { display: flex; flex-wrap: wrap; text-align: left; }
                .print-info-item { width: 50%; margin-bottom: 10px; }
                .print-info-item .label { font-weight: bold; }
                .print-table-container { margin-bottom: 20px; }
                .print-table-container h2 { font-size: 18px; font-weight: bold; margin-bottom: 10px; }
                .print-table { width: 100%; border-collapse: collapse; border: 1px solid #000; table-layout: fixed; }
                .print-table th, .print-table td { border: 1px solid #000; padding: 5px; text-align: center; font-size: 12px; word-break: break-word; vertical-align: middle; }
                .print-table th { background-color: #f0f0f0; }
                .print-footer { margin-top: 30px; }
                .print-signature { display: flex; justify-content: space-between; }
                .signature-item { margin-bottom: 10px; }
                .signature-line { display: inline-block; min-width: 150px; border-bottom: 1px solid #000; text-align: center; }
                
                /* 设置各列的宽度 */
                .print-table th:nth-child(1), .print-table td:nth-child(1) { width: 8%; } /* 物料编码 */
                .print-table th:nth-child(2), .print-table td:nth-child(2) { width: 10%; } /* 物料名称 */
                .print-table th:nth-child(3), .print-table td:nth-child(3) { width: 7%; } /* 物料类型 */
                .print-table th:nth-child(4), .print-table td:nth-child(4) { width: 8%; } /* 规格 */
                .print-table th:nth-child(5), .print-table td:nth-child(5) { width: 5%; } /* 单位 */
                .print-table th:nth-child(6), .print-table td:nth-child(6) { width: 12%; } /* 计划入库仓库/库位 */
                .print-table th:nth-child(7), .print-table td:nth-child(7) { width: 12%; } /* 实际入库仓库/库位 */
                .print-table th:nth-child(8), .print-table td:nth-child(8) { width: 8%; } /* 计划数量 */
                .print-table th:nth-child(9), .print-table td:nth-child(9) { width: 8%; } /* 实际数量 */
                .print-table th:nth-child(10), .print-table td:nth-child(10) { width: 10%; } /* 单位成本 */
                .print-table th:nth-child(11), .print-table td:nth-child(11) { width: 12%; } /* 状态 */
                
                /* 调拨入库模式下的列宽设置 */
                .transfer-mode .print-table th:nth-child(1), .transfer-mode .print-table td:nth-child(1) { width: 8%; } /* 物料编码 */
                .transfer-mode .print-table th:nth-child(2), .transfer-mode .print-table td:nth-child(2) { width: 10%; } /* 物料名称 */
                .transfer-mode .print-table th:nth-child(3), .transfer-mode .print-table td:nth-child(3) { width: 7%; } /* 物料类型 */
                .transfer-mode .print-table th:nth-child(4), .transfer-mode .print-table td:nth-child(4) { width: 5%; } /* 单位 */
                .transfer-mode .print-table th:nth-child(5), .transfer-mode .print-table td:nth-child(5) { width: 15%; } /* 源仓库/源库位 */
                .transfer-mode .print-table th:nth-child(6), .transfer-mode .print-table td:nth-child(6) { width: 15%; } /* 计划入库仓库/库位 */
                .transfer-mode .print-table th:nth-child(7), .transfer-mode .print-table td:nth-child(7) { width: 15%; } /* 实际入库仓库/库位 */
                .transfer-mode .print-table th:nth-child(8), .transfer-mode .print-table td:nth-child(8) { width: 8%; } /* 计划数量 */
                .transfer-mode .print-table th:nth-child(9), .transfer-mode .print-table td:nth-child(9) { width: 8%; } /* 实际数量 */
                .transfer-mode .print-table th:nth-child(10), .transfer-mode .print-table td:nth-child(10) { width: 9%; } /* 状态 */
                
                @media print {
                  .no-print { display: none; }
                }
              </style>
            </head>
            <body>
              <div class="no-print" style="padding: 20px; text-align: center;">
                <button onclick="window.print()">打印全部</button>
              </div>
              <div id="print-container"></div>
            </body>
          </html>
        `)
        
        // 加载每个入库单并添加到打印窗口
        const promises = ids.map(id => this.loadInboundOrderData(id))
        Promise.all(promises)
          .then(orders => {
            const container = printWindow.document.getElementById('print-container')
            
            orders.forEach((orderData, index) => {
              if (!orderData || !orderData.order) return
              
              const { order, details } = orderData
              const content = this.generateOrderHtml(order, details)
              const pageDiv = printWindow.document.createElement('div')
              pageDiv.innerHTML = content
              if (index < orders.length - 1) {
                pageDiv.className = 'page-break'
              }
              container.appendChild(pageDiv)
            })
          })
          .catch(err => {
            console.error('加载入库单数据失败', err)
            printWindow.close()
            this.$message.error('加载入库单数据失败')
          })
      },
      
      // 生成入库单HTML内容
      generateOrderHtml(order, details) {
        let detailsHtml = ''
        
        if (details && details.length > 0) {
          details.forEach(detail => {
            if (order.businessType !== '13') {
              detailsHtml += `
                <tr>
                  <td>${detail.materialCode || ''}</td>
                  <td>${detail.materialName || ''}</td>
                  <td>${detail.materialTypeName || ''}</td>
                  <td>${detail.specification || ''}</td>
                  <td>${detail.unit || ''}</td>
                  <td>${detail.planWarehouseName || ''}/${detail.planLocationName || ''}</td>
                  <td>${detail.actualWarehouseName || ''} ${detail.actualLocationName || ''}</td>
                  <td>${detail.planQuantity || ''}</td>
                  <td>${detail.actualQuantity || ''}</td>
                  <td>${detail.unitCost || '0.00'}</td>
                  <td>${this.getDetailStatus(detail)}</td>
                </tr>
              `
            } else {
              detailsHtml += `
                <tr>
                  <td>${detail.materialCode || ''}</td>
                  <td>${detail.materialName || ''}</td>
                  <td>${detail.materialTypeName || ''}</td>
                  <td>${detail.unit || ''}</td>
                  <td>${detail.sourceWarehouseName || '-'}/${detail.sourceLocationName || '-'}</td>
                  <td>${detail.planWarehouseName || ''}/${detail.planLocationName || ''}</td>
                  <td>${detail.actualWarehouseName || ''} ${detail.actualLocationName || ''}</td>
                  <td>${detail.planQuantity || ''}</td>
                  <td>${detail.actualQuantity || ''}</td>
                  <td>${this.getDetailStatus(detail)}</td>
                </tr>
              `
            }
          })
        } else {
          detailsHtml = `<tr><td colspan="${order.businessType === '13' ? 10 : 11}">无明细数据</td></tr>`
        }
        
        // 格式化计划入库时间，确保格式为YYYY-MM-DD
        let planInboundTimeValue = ''
        if (order.planInboundTime) {
          // 无论输入是什么类型，都统一格式化为YYYY-MM-DD
          planInboundTimeValue = moment(order.planInboundTime).format('YYYY-MM-DD')
        }
        
        return `
          <div class="print-content${order.businessType === '13' ? ' transfer-mode' : ''}">
            <div class="print-header">
              <h1>入库单</h1>
              <div class="print-info">
                <div class="print-info-item">
                  <span class="label">入库单号：</span>
                  <span class="value">${order.inboundNo || ''}</span>
                </div>
                <div class="print-info-item">
                  <span class="label">计划入库日期：</span>
                  <span class="value">
                    <span class="signature-line">${planInboundTimeValue}</span>
                  </span>
                </div>
                <div class="print-info-item">
                  <span class="label">业务类型：</span>
                  <span class="value">${order.businessTypeName || ''}</span>
                </div>
                <div class="print-info-item">
                  <span class="label">业务单号：</span>
                  <span class="value">${order.businessNo || ''}</span>
                </div>
                <div class="print-info-item">
                  <span class="label">批次号：</span>
                  <span class="value">${order.batchNo || ''}</span>
                </div>
                <div class="print-info-item">
                  <span class="label">入库单状态：</span>
                  <span class="value">${order.statusName || ''}</span>
                </div>
                <div class="print-info-item" style="width: 100%">
                  <span class="label">备注：</span>
                  <span class="value">${order.remark || ''}</span>
                </div>
              </div>
            </div>
            
            <!-- 物料明细信息 -->
            <div class="print-table-container">
              <h2>物料明细信息</h2>
              <table class="print-table">
                <thead>
                  <tr>
                    ${order.businessType !== '13' ? `
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>物料类型</th>
                    <th>规格</th>
                    <th>单位</th>
                    <th>计划入库仓库/库位</th>
                    <th>实际入库仓库/库位</th>
                    <th>计划数量</th>
                    <th>实际数量</th>
                    <th>单位成本</th>
                    <th>状态</th>
                    ` : `
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>物料类型</th>
                    <th>单位</th>
                    <th>原仓库/原库位</th>
                    <th>计划入库仓库/库位</th>
                    <th>实际入库仓库/库位</th>
                    <th>计划数量</th>
                    <th>实际数量</th>
                    <th>状态</th>
                    `}
                  </tr>
                </thead>
                <tbody>
                  ${detailsHtml}
                </tbody>
              </table>
            </div>
            
            <!-- 汇总信息 -->
            <div class="print-table-container">
              <h2>汇总信息</h2>
              <table class="print-table">
                <thead>
                  <tr>
                    <th width="33%">总计划入库数量</th>
                    <th width="33%">总实际入库数量</th>
                    <th width="34%">创建时间</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>${order.totalPlanQuantity || ''}</td>
                    <td></td>
                    <td>${order.createTime ? moment(order.createTime).format('YYYY-MM-DD') : ''}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <div class="print-footer">
              <div class="print-signature">
                <div class="signature-item">
                  <span>仓库管理员：</span>
                  <span class="signature-line"></span>
                </div>
                <div class="signature-item">
                  <span>入库操作人：</span>
                  <span class="signature-line"></span>
                </div>
                <div class="signature-item">
                  <span>入库日期：</span>
                  <span class="signature-line"></span>
                </div>
              </div>
            </div>
          </div>
        `
      },
      
      // 加载单个入库单数据并返回Promise
      loadInboundOrderData(id) {
        return new Promise((resolve, reject) => {
          // 首先获取入库单主数据
          getAction(`${this.url.getInboundOrder}?id=${id}`).then(res => {
            if (res.success) {
              const order = res.result || {}
              
              // 然后获取入库单明细数据
              getAction(`${this.url.getDetailList}?inboundOrderId=${id}`).then(detailRes => {
                if (detailRes.success) {
                  resolve({
                    order: order,
                    details: detailRes.result || []
                  })
                } else {
                  resolve({
                    order: order,
                    details: []
                  })
                }
              }).catch(err => {
                console.error('获取入库单明细失败', err)
                resolve({
                  order: order,
                  details: []
                })
              })
            } else {
              reject(new Error(res.message || '加载入库单数据失败'))
            }
          }).catch(err => {
            reject(err)
          })
        })
      },
      
      loadData(id) {
        this.confirmLoading = true
        
        // 清空数据
        this.model = {}
        this.detailList = []
        this.planInboundTime = null
        
        // 使用loadInboundOrderData方法加载数据
        this.loadInboundOrderData(id).then(data => {
          this.model = data.order
          
          // 为每条明细添加编辑状态标记
          this.detailList = (data.details || []).map(detail => ({
            ...detail
          }))
          
          // 设置计划入库时间，确保格式为YYYY-MM-DD
          if (this.model.planInboundTime) {
            try {
              // 先格式化为纯日期
              const formattedDate = moment(this.model.planInboundTime).format('YYYY-MM-DD')
              this.model.planInboundTime = formattedDate
              this.planInboundTime = moment(formattedDate)
            } catch (error) {
              console.error('日期格式化失败:', error)
              // 如果日期格式化失败，使用当前日期
              const today = moment().format('YYYY-MM-DD')
              this.model.planInboundTime = today
              this.planInboundTime = moment(today)
            }
          }
        }).catch(err => {
          this.$message.warning(err.message || '获取入库单数据失败')
        }).finally(() => {
          this.confirmLoading = false
        })
      },

      // 打印
      handlePrint() {
        // 创建新窗口进行打印，避免影响当前页面
        const printWindow = window.open('', '_blank', 'width=800,height=600')
        const originalElement = document.getElementById('printArea')
        const tempContainer = document.createElement('div')
        tempContainer.innerHTML = originalElement.innerHTML
        
        // 查找日期选择器元素并替换为纯文本
        const datePickerElement = tempContainer.querySelector('.date-picker-wrapper')
        if (datePickerElement) {
          // 确保日期格式为YYYY-MM-DD
          let dateValue = ''
          if (this.model.planInboundTime) {
            dateValue = moment(this.model.planInboundTime).format('YYYY-MM-DD')
          }
          const textNode = document.createElement('span')
          textNode.className = 'signature-line'
          textNode.textContent = dateValue
          if (datePickerElement.parentNode) {
            datePickerElement.parentNode.replaceChild(textNode, datePickerElement)
          }
        }

        printWindow.document.write(`
          <!DOCTYPE html>
          <html>
          <head>
            <title>入库单打印</title>
            <style>
              body { margin: 0; padding: 20px; font-family: Arial, sans-serif; }
              .print-content { padding: 20px; background-color: #fff; }
              .print-header { text-align: center; margin-bottom: 20px; }
              .print-header h1 { font-size: 24px; font-weight: bold; margin-bottom: 20px; }
              .print-info { display: flex; flex-wrap: wrap; text-align: left; }
              .print-info-item { width: 50%; margin-bottom: 10px; }
              .print-info-item .label { font-weight: bold; }
              .print-table-container { margin-bottom: 20px; }
              .print-table-container h2 { font-size: 18px; font-weight: bold; margin-bottom: 10px; }
              .print-table { width: 100%; border-collapse: collapse; border: 1px solid #000; table-layout: fixed; }
              .print-table th, .print-table td { border: 1px solid #000; padding: 5px; text-align: center; font-size: 12px; word-break: break-word; vertical-align: middle; }
              .print-table th { background-color: #f0f0f0; }
              .print-footer { margin-top: 30px; }
              .print-signature { display: flex; justify-content: space-between; }
              .signature-item { margin-bottom: 10px; }
              .signature-line { display: inline-block; min-width: 150px; border-bottom: 1px solid #000; text-align: center; }
              .print-table th:nth-child(1), .print-table td:nth-child(1) { width: 8%; }
              .print-table th:nth-child(2), .print-table td:nth-child(2) { width: 10%; }
              .print-table th:nth-child(3), .print-table td:nth-child(3) { width: 7%; }
              .print-table th:nth-child(4), .print-table td:nth-child(4) { width: 8%; }
              .print-table th:nth-child(5), .print-table td:nth-child(5) { width: 5%; }
              .print-table th:nth-child(6), .print-table td:nth-child(6) { width: 12%; }
              .print-table th:nth-child(7), .print-table td:nth-child(7) { width: 12%; }
              .print-table th:nth-child(8), .print-table td:nth-child(8) { width: 8%; }
              .print-table th:nth-child(9), .print-table td:nth-child(9) { width: 8%; }
              .print-table th:nth-child(10), .print-table td:nth-child(10) { width: 10%; }
              .print-table th:nth-child(11), .print-table td:nth-child(11) { width: 12%; }
              .transfer-mode .print-table th:nth-child(1), .transfer-mode .print-table td:nth-child(1) { width: 8%; }
              .transfer-mode .print-table th:nth-child(2), .transfer-mode .print-table td:nth-child(2) { width: 10%; }
              .transfer-mode .print-table th:nth-child(3), .transfer-mode .print-table td:nth-child(3) { width: 7%; }
              .transfer-mode .print-table th:nth-child(4), .transfer-mode .print-table td:nth-child(4) { width: 5%; }
              .transfer-mode .print-table th:nth-child(5), .transfer-mode .print-table td:nth-child(5) { width: 15%; }
              .transfer-mode .print-table th:nth-child(6), .transfer-mode .print-table td:nth-child(6) { width: 15%; }
              .transfer-mode .print-table th:nth-child(7), .transfer-mode .print-table td:nth-child(7) { width: 15%; }
              .transfer-mode .print-table th:nth-child(8), .transfer-mode .print-table td:nth-child(8) { width: 8%; }
              .transfer-mode .print-table th:nth-child(9), .transfer-mode .print-table td:nth-child(9) { width: 8%; }
              .transfer-mode .print-table th:nth-child(10), .transfer-mode .print-table td:nth-child(10) { width: 9%; }
              @media print {
                @page { margin: 0.5in; }
                body { margin: 0; }
              }
            </style>
          </head>
          <body>
            ${tempContainer.innerHTML}
          </body>
          </html>
        `)

        printWindow.document.close()

        // 等待内容加载完成后打印
        printWindow.onload = function() {
          printWindow.print()
          printWindow.close()
        }
      },

      // 导出PDF
      handleExport() {
        this.confirmLoading = true
        
        // 显示加载提示
        this.$message.loading('正在生成PDF，请稍候...', 0);
        
        // 获取原始元素
        const originalElement = document.getElementById('printArea')
        
        // 创建一个临时容器，用于存放处理后的内容
        const tempContainer = document.createElement('div')
        tempContainer.innerHTML = originalElement.innerHTML
        tempContainer.style.width = originalElement.offsetWidth + 'px'
        tempContainer.style.padding = '20px'
        tempContainer.style.background = '#fff'
        tempContainer.style.position = 'absolute'
        tempContainer.style.left = '-9999px'
        tempContainer.style.top = '-9999px'
        
        // 查找日期选择器元素并替换为纯文本
        const datePickerElement = tempContainer.querySelector('.date-picker-wrapper')
        if (datePickerElement) {
          // 确保日期格式为YYYY-MM-DD
          let dateValue = ''
          if (this.model.planInboundTime) {
            dateValue = moment(this.model.planInboundTime).format('YYYY-MM-DD')
          }
          const textNode = document.createElement('span')
          textNode.className = 'signature-line'
          textNode.textContent = dateValue
          if (datePickerElement.parentNode) {
            datePickerElement.parentNode.replaceChild(textNode, datePickerElement)
          }
        }
        
        // 将临时容器添加到文档中
        document.body.appendChild(tempContainer)
        
        // 使用setTimeout确保DOM已完全渲染
        setTimeout(() => {
          html2canvas(tempContainer, {
            scale: 2,
            useCORS: true,
            logging: false,
            allowTaint: true,
            backgroundColor: '#ffffff'
          }).then(canvas => {
            // 移除临时容器
            document.body.removeChild(tempContainer)
            
            const imgData = canvas.toDataURL('image/png')
            const pdf = new jsPDF({
              orientation: 'landscape',
              unit: 'mm',
              format: 'a4'
            })
            const imgWidth = 297 // A4横向宽度
            const pageHeight = 210 // A4横向高度
            const imgHeight = canvas.height * imgWidth / canvas.width
            let heightLeft = imgHeight
            let position = 0
            
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
            heightLeft -= pageHeight
            
            while (heightLeft > 0) {
              position = heightLeft - imgHeight
              pdf.addPage()
              pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
              heightLeft -= pageHeight
            }
            
            pdf.save(`入库单-${this.model.inboundNo || '未命名'}.pdf`)
            this.confirmLoading = false
            // 关闭加载提示
            this.$message.destroy();
            this.$message.success('PDF导出成功');
          }).catch(error => {
            // 移除临时容器
            if (document.body.contains(tempContainer)) {
              document.body.removeChild(tempContainer)
            }
            console.error('导出PDF失败', error)
            this.$message.error(`导出PDF失败: ${error.message || '未知错误'}`)
            this.confirmLoading = false
            // 关闭加载提示
            this.$message.destroy();
          })
        }, 1000) // 延长延迟时间，确保DOM渲染完成
      },
      
      handleCancel() {
        this.visible = false
      }
    }
  }
</script>

<style>
/* 全局样式，确保表格边框正确显示 */
.custom-table {
  border: 1px solid #e8e8e8 !important;
}

.custom-table .ant-table-thead > tr > th,
.custom-table .ant-table-tbody > tr > td {
  border-right: 1px solid #e8e8e8 !important;
  border-bottom: 1px solid #e8e8e8 !important;
}

.custom-table .ant-table-thead > tr > th {
  background-color: #f0f0f0 !important;
  font-weight: bold !important;
}
</style>

<style scoped>
.print-content {
  padding: 20px;
  background-color: #fff;
}

.print-header {
  text-align: center;
  margin-bottom: 20px;
}

.print-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.print-info {
  display: flex;
  flex-wrap: wrap;
  text-align: left;
}

.print-info-item {
  width: 50%;
  margin-bottom: 10px;
}

.print-info-item .label {
  font-weight: bold;
}

.print-table-container {
  margin-bottom: 20px;
}

.print-table-container h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.print-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #000;
  table-layout: fixed;
}

.print-table th,
.print-table td {
  border: 1px solid #000;
  padding: 5px;
  text-align: center; /* 调小字体使表格更紧凑 */
  font-size: 12px;
  word-break: break-word;
  vertical-align: middle;
}

.print-table th {
  background-color: #f0f0f0;
}

/* 设置各列的宽度 */
.print-table th:nth-child(1), .print-table td:nth-child(1) { width: 8%; } /* 物料编码 */
.print-table th:nth-child(2), .print-table td:nth-child(2) { width: 10%; } /* 物料名称 */
.print-table th:nth-child(3), .print-table td:nth-child(3) { width: 7%; } /* 物料类型 */
.print-table th:nth-child(4), .print-table td:nth-child(4) { width: 8%; } /* 规格 */
.print-table th:nth-child(5), .print-table td:nth-child(5) { width: 5%; } /* 单位 */
.print-table th:nth-child(6), .print-table td:nth-child(6) { width: 12%; } /* 计划入库仓库/库位 */
.print-table th:nth-child(7), .print-table td:nth-child(7) { width: 12%; } /* 实际入库仓库/库位 */
.print-table th:nth-child(8), .print-table td:nth-child(8) { width: 8%; } /* 计划数量 */
.print-table th:nth-child(9), .print-table td:nth-child(9) { width: 8%; } /* 实际数量 */
.print-table th:nth-child(10), .print-table td:nth-child(10) { width: 10%; } /* 单位成本 */
.print-table th:nth-child(11), .print-table td:nth-child(11) { width: 12%; } /* 状态 */

/* 调拨入库模式下的列宽设置 */
.transfer-mode .print-table th:nth-child(1), .transfer-mode .print-table td:nth-child(1) { width: 8%; } /* 物料编码 */
.transfer-mode .print-table th:nth-child(2), .transfer-mode .print-table td:nth-child(2) { width: 10%; } /* 物料名称 */
.transfer-mode .print-table th:nth-child(3), .transfer-mode .print-table td:nth-child(3) { width: 7%; } /* 物料类型 */
.transfer-mode .print-table th:nth-child(4), .transfer-mode .print-table td:nth-child(4) { width: 5%; } /* 单位 */
.transfer-mode .print-table th:nth-child(5), .transfer-mode .print-table td:nth-child(5) { width: 15%; } /* 源仓库/源库位 */
.transfer-mode .print-table th:nth-child(6), .transfer-mode .print-table td:nth-child(6) { width: 15%; } /* 计划入库仓库/库位 */
.transfer-mode .print-table th:nth-child(7), .transfer-mode .print-table td:nth-child(7) { width: 15%; } /* 实际入库仓库/库位 */
.transfer-mode .print-table th:nth-child(8), .transfer-mode .print-table td:nth-child(8) { width: 8%; } /* 计划数量 */
.transfer-mode .print-table th:nth-child(9), .transfer-mode .print-table td:nth-child(9) { width: 8%; } /* 实际数量 */
.transfer-mode .print-table th:nth-child(10), .transfer-mode .print-table td:nth-child(10) { width: 9%; } /* 状态 */

.print-footer {
  margin-top: 30px;
}

.print-signature {
  display: flex;
  justify-content: space-between;
}

.signature-item {
  margin-bottom: 10px;
}

.signature-line {
  display: inline-block;
  min-width: 150px;
  border-bottom: 1px solid #000;
  text-align: center;
}

.date-picker-wrapper {
  display: inline-block;
  cursor: pointer;
}

.print-actions {
  margin-top: 20px;
  text-align: center;
}

@media print {
  .print-actions {
    display: none;
  }
}

/* 表格容器样式 */
.table-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

.custom-table-border {
  border: 2px solid #1890ff;
}

/* 添加可编辑行样式 */
.editable-row {
  background-color: #e6f7ff;
}

.editable-row:hover {
  cursor: pointer;
}

/* 偶数行样式 */
.even-row {
  background-color: #f9f9f9;
}

/* 编辑按钮样式 */
.ant-btn-link {
  padding: 0 4px;
}
</style> 